<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import http from '@/http'
import { ro } from 'element-plus/es/locale';

// 部门和医生数据
const departments = ref();
let doctors = ref();

// 搜索参数
const searchParams = ref({
    department: '',
    doctor: ''
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(2) // 每页显示3条数据

// 日期范围的默认值（一周）
const getDefaultDateRange = () => {
    const today = dayjs()
    const startDate = today.startOf('week')
    const endDate = today.endOf('week')
    return [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')]
}

const defaultDateRange = ref(getDefaultDateRange())
const dateRange = ref(getDefaultDateRange())

// 表头样式
const headerCellStyle = {
    background: '#f5f7fa',
    color: '#606266',
    fontWeight: 'bold'
}

// 格式化日期范围显示
const formatDateRange = computed(() => {
    console.log(dateRange.value, '1244');
    if (!dateRange.value || dateRange.value.length !== 2) return ''
    const [start, end] = dateRange.value
    return `${start}(${getDayOfWeek(start)})~${end}(${getDayOfWeek(end)})`
})

// 获取星期几
function getDayOfWeek(dateStr) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const date = dayjs(dateStr)
    return weekdays[date.day()]
}

// 计算当前选择日期范围内的日期
const weekDays = computed(() => {
    if (!dateRange.value || dateRange.value.length !== 2) return []

    const days = []
    const startDate = dayjs(dateRange.value[0])
    const endDate = dayjs(dateRange.value[1])

    let currentDate = startDate
    while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {
        days.push({
            date: currentDate.format('YYYY-MM-DD'),
            dayOfWeek: currentDate.day()
        })
        currentDate = currentDate.add(1, 'day')
    }

    return days
})

// 格式化显示日期
function formatDay(dateStr) {
    const date = dayjs(dateStr)
    const month = date.month() + 1
    const day = date.date()
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const dayOfWeek = weekdays[date.day()]
    return `${month}-${day}(${dayOfWeek})`
}

// 模拟的排班数据
const scheduleData = ref([
    {
        doctor: '熊猫',
        department: '内科',
        schedules: [
            { date: '2023-10-16', timeSlot: 1, type: '门诊' },
            { date: '2023-10-16', timeSlot: 2, type: '门诊' },
            { date: '2023-10-16', timeSlot: 3, type: '门诊' }
        ]
    },
    {
        doctor: '李时珍',
        department: '外科',
        schedules: [
            { date: '2023-10-16', timeSlot: 1, type: '门诊' },
            { date: '2023-10-16', timeSlot: 2, type: '门诊' },
            { date: '2023-10-16', timeSlot: 3, type: '门诊' }
        ]
    },
    {
        doctor: '孙思邈',
        department: '儿科',
        schedules: []
    },
    {
        doctor: '华佗',
        department: '妇科',
        schedules: []
    },
    {
        doctor: '皇甫谧',
        department: '眼科',
        schedules: []
    },
    {
        doctor: '张仲景',
        department: '内科',
        schedules: [
            { date: '2023-10-17', timeSlot: 1, type: '门诊' }
        ]
    },
    {
        doctor: '扁鹊',
        department: '外科',
        schedules: [
            { date: '2023-10-18', timeSlot: 2, type: '门诊' }
        ]
    }
])

// 筛选后的表格数据
const filteredTableData = computed(() => {
    let result = [...scheduleData.value]

    if (searchParams.value.department) {
        result = result.filter(item => item.department === searchParams.value.department)
    }

    if (searchParams.value.doctor) {
        result = result.filter(item => item.doctor === searchParams.value.doctor)
    }

    return result
})

// 分页后的表格数据
const paginatedTableData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredTableData.value.slice(start, end)
})

// 检查医生在特定日期和时段是否有排班
function hasSchedule(doctor, date, timeSlot) {
    return doctor.schedules.some(s =>
        s.date === date && s.timeSlot === timeSlot
    )
}

// 获取排班文本
function getScheduleText(doctor, date, timeSlot) {
    const schedule = doctor.schedules.find(s =>
        s.date === date && s.timeSlot === timeSlot
    )
    return schedule ? schedule.type : ''
}

// 处理日期变化
function handleDateChange(val) {
    // 这里可以根据新的日期范围重新获取排班数据
    console.log('日期范围变化:', val)
    currentPage.value = 1 // 重置页码
    //调用查询方法
    getScheduling();
}

// 处理搜索
function handleSearch() {
    // 根据搜索条件筛选数据
    console.log('搜索条件:', searchParams.value)
    currentPage.value = 1 // 重置页码
}

// 重置搜索
function resetSearch() {
    searchParams.value = {
        department: '',
        doctor: ''
    }
    currentPage.value = 1 // 重置页码
}

// 处理页码大小变化
function handleSizeChange(val) {
    pageSize.value = val
    currentPage.value = 1 // 重置页码
    //调用查询
    getScheduling();
}

// 处理当前页变化
function handleCurrentChange(val) {
    currentPage.value = val
    getScheduling();
}
// 监听搜索条件变化，重置页码
watch(searchParams, () => {
    currentPage.value = 1
      getPhysicianName(searchParams.value.department);
}, { deep: true })

// 初始化数据
onMounted(() => {
    // 初始化排班数据，在实际应用中，这里应该从API获取数据
    getScheduling();
    // 使用当前日期范围初始化数据
    updateScheduleData()
    //获取医生和科室数据
    getUserDept();
    //获取门诊消息
    fetchDictData("his_scheduling_type")
})

// 更新排班数据
function updateScheduleData() {
    // 模拟从API获取数据的过程
    // 在实际应用中，这里应该调用后端API
    console.log('更新排班数据，日期范围:', dateRange.value)
}
//获取医生和科室信息
function getUserDept(){
      //查询所属科室
    getdept();
    //查询医生名称
    getPhysicianName(searchParams.value.department);
}
function getdept() {
    //发送http请求，获取科室信息
    http.get("/dept/getdept").then((res) => {
            departments.value = res;
    }).catch((res) => {
        console.log("失败");
    });
}
function getPhysicianName(v2: any) {
    http.get("/user/getPhysicianName?DeptId=" + v2).then((res) => {
        console.log("成功", res);
        doctors.value = res;
    }).catch((res) => {
        console.log("失败");
    });
}
let Pages=ref([])
let total=ref()
//获取排班数据
function getScheduling() {
    console.log(dateRange.value,"时间")
    let startDate2=ref(dateRange.value[0].toString());
    let dateRange2=ref(dateRange.value[1].toString());
    http.get('/scheduling/getScheduling', {
        params: {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            deptId: searchParams.value.department,
            userId: searchParams.value.doctor,
            startDate:startDate2.value ,
            endDate: dateRange2.value
        }
    }).then((res)=>{
        Pages.value=res.list
        total.value=res.total
        
    })
}
//

 // 上午时段
function hasMorningSchedule(row, date) {
  return (row.fhisSchedulingUserDepts || []).some(
    item => item.schedulingDay === date && item.subsectionType === '1' // 时段类型判断
  );
}

function getMorningSchedule(row, date) {
  const schedule = (row.fhisSchedulingUserDepts || []).find(
    item => item.schedulingDay === date && item.subsectionType === '1'
  );
  
  // 根据 schedulingType 返回
  return schedule?.schedulingType === '1' 
    ? '门诊' 
    : schedule?.schedulingType === '2' 
      ? '急诊' 
      : '';
}

// 中午时段
function hasAfternoonSchedule(row, date) {
  return (row.fhisSchedulingUserDeptszhho || []).some(
    item => item.schedulingDay === date && item.subsectionType === '2'
  );
}

function getAfternoonSchedule(row, date) {
  const schedule = (row.fhisSchedulingUserDeptszhho || []).find(
    item => item.schedulingDay === date && item.subsectionType === '2'
  );
  
  return schedule?.schedulingType === '1' 
    ? '门诊' 
    : schedule?.schedulingType === '2' 
      ? '急诊' 
      : '';
}

// 晚上时段（关键修正）
function hasEveningSchedule(row, date) {
  return (row.fhisSchedulingUserDeptswan || []).some(
    item => item.schedulingDay === date && item.subsectionType === '3' // 时段类型匹配
  );
}

function getEveningSchedule(row, date) {
  const schedule = (row.fhisSchedulingUserDeptswan || []).find(
    item => item.schedulingDay === date && item.subsectionType === '3'
  );
  
  return schedule?.schedulingType === '1' 
    ? '门诊' 
    : schedule?.schedulingType === '2' 
      ? '急诊' 
      : '';
}


//修改
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  }
});

const tableData = ref([
{
    title: '上午',
    timeSlot: 1, // 添加时段标识
    schedules: {} // 初始化空对象
  },
  {
    title: '下午',  
    timeSlot: 2,
    schedules: {}
  },
  {
    title: '晚上', 
    timeSlot: 3,
    schedules: {}
  }
]);

const submitForm = () => {
  // 这里可以添加表单提交的逻辑，比如将数据发送到后端
  console.log('提交表单', tableData.value);
};
const isModalVisible = ref(false);
watch (isModalVisible,()=>{
    if(!isModalVisible.value){
        getScheduling();
    }
})
//获取门诊消息
// 获取时段类型字典
let timePeriod = ref([])
const fetchDictData = async (dictType) => {
  await http.get('/api/dict/data/' + dictType).then((res) => {
     // 在原始数据基础上添加新项
     timePeriod.value = [...res, { 
      dict_value: '', 
      dict_label: '无', 
    }];
  }).catch((error) => {
    console.error('获取字典数据失败:', error);
  })
};
// 添加状态变量
const currentEditingDoctor = ref<{
  userId: string;
  userName: string;
  deptId: String;
}>({ userId: '', userName: '',deptId:'' });
//
// 在 <script setup> 中添加以下方法
const handleScheduleChange = async (row: any, date: string,schedulingType :String) => {
    let scheDuling=ref({
        userId:currentEditingDoctor.value.userId,
        deptId:currentEditingDoctor.value.deptId,
        schedulingDay:date,
        subsectionType:row.timeSlot,
        schedulingType:schedulingType
    })
    
    //发送http请求
    http.post("/scheduling/addScheduling",scheDuling.value).then((res)=>{
        console.log("成功")
    }).catch((res)=>{
        console.log("失败")
    })

};
//// 修改打开模态框的方法
const openEditModal = (row: any) => {
  isModalVisible.value = true;

  currentEditingDoctor.value = {
    userId: row.userId,
    userName: row.userName,
    deptId: row.deptId
  };
   // 验证传入数据
   if (!row?.userId || !row?.userName) {
    console.error('无效的行数据:', row);
    return;
  }

  currentEditingDoctor.value = { ...row }; // 使用展开运算符确保响应性
  
  // 调试输出
  console.log('设置后的响应式对象:', currentEditingDoctor.value);
  console.log('序列化结果:', JSON.parse(JSON.stringify(currentEditingDoctor.value)))
   // 根据当前行的排班数据设置tableData的schedules默认值
   weekDays.value.forEach(day => {
    const morningSchedule = getMorningSchedule(row, day.date);
    const afternoonSchedule = getAfternoonSchedule(row, day.date);
    const eveningSchedule = getEveningSchedule(row, day.date);
    tableData.value[0].schedules[day.date] = morningSchedule? getDictValueByLabel(timePeriod.value, morningSchedule) : '';
    tableData.value[1].schedules[day.date] = afternoonSchedule? getDictValueByLabel(timePeriod.value, afternoonSchedule) : '';
    tableData.value[2].schedules[day.date] = eveningSchedule? getDictValueByLabel(timePeriod.value, eveningSchedule) : '';
  });
  console.log(row)
 
  console.log(tableData.value)
  console.log("用户值"+currentEditingDoctor.value)
}
// 辅助函数：根据标签获取字典值
function getDictValueByLabel(dictArray, label) {
  return dictArray.find(item => item.dict_label === label)?.dict_value || '';
}
</script>
<template>
    <div class="schedule-container">
        <div class="search-area">
            <div class="search-item">
                <span class="label">科室名称</span>
                <el-select v-model="searchParams.department" placeholder="请选择科室" style="width: 200px;" clearable>
                    <el-option value="">全部</el-option>
                    <el-option v-for="item in departments" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
                </el-select>
            </div>
            <div class="search-item">
                <span class="label">医生名称</span>
                <el-select v-model="searchParams.doctor" placeholder="请选择医生" style="width: 200px;" clearable>
                    <el-option value="">全部</el-option>
                    <el-option v-for="item in doctors" :key="item.userId" :label="item.userName" :value="item.userId" />
                </el-select>
            </div>
            <el-button type="primary" :icon="Search" @click="getScheduling()">查询</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </div>

        <div class="date-picker-area">
            <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" :default-value="defaultDateRange"
                @change="handleDateChange" />
            <div class="date-display">{{ formatDateRange }}</div>
        </div>
        
        <el-table :data="Pages" border :header-cell-style="headerCellStyle">
  <el-table-column prop="userName" label="医生" width="100" align="center" />
  <el-table-column prop="deptName" label="科室" width="100" align="center" />
  <el-table-column label="时段/日期" width="100" align="center">
                <template #default="scope">
                    <div class="time-slots">
                        <div>上午</div>
                        <div>下午</div>
                        <div>晚上</div>
                    </div>
                </template>
            </el-table-column>
  <!-- 日期列 -->
  <el-table-column 
    v-for="(day, index) in weekDays" 
    :key="index" 
    :label="formatDay(day.date)"
    align="center">
    <template #default="{ row }">
      <div class="schedule-slots">
        <!-- 上午 -->
        <div class="slot-item" 
             :class="{ 'has-schedule': hasMorningSchedule(row, day.date) }">
          {{ getMorningSchedule(row, day.date) }}
        </div>
        <!-- 中午 -->
        <div class="slot-item" 
             :class="{ 'has-schedule': hasAfternoonSchedule(row, day.date) }">
          {{ getAfternoonSchedule(row, day.date) }}
        </div>
        <!-- 晚上 -->
        <div class="slot-item" 
             :class="{ 'has-schedule': hasEveningSchedule(row, day.date) }">
          {{ getEveningSchedule(row, day.date) }}
        </div>
      </div>
    </template>
  </el-table-column>
  <el-table-column prop="deptName" label="操作" width="100" align="center" >
    <template #default="scope">
 <el-button type="primary" @click="openEditModal(scope.row)">修改</el-button>
    </template>
    </el-table-column>
</el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>
    <!-- 修改模态框 -->
    <el-dialog
    title="修改【扁鹊】排班信息"
v-model="isModalVisible"
    width="800px"
    center
  >
    <el-table :data="tableData" style="width: 100%;">
      <el-table-column label="时间/日期" width="120">
        <template #default="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
     <!-- 动态生成日期列 -->
  <el-table-column 
    v-for="(day, index) in weekDays"
    :key="index"
    :label="`${day.date}(${getDayOfWeek(day.date)})`"
    width="120">
    <template #default="scope">
      <el-select 
        v-model="scope.row.schedules[day.date]" 
        placeholder="请选择"
        @change="handleScheduleChange(scope.row, day.date,scope.row.schedules[day.date])">
        <el-option 
          v-for="opt in timePeriod" 
          :key="opt.dict_value"
          :label="opt.dict_label"
          :value="opt.dict_value"/>
      </el-select>
    </template>
  </el-table-column>
    </el-table>
    <!-- <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template> -->
  </el-dialog>
</template>
<style scoped>
.schedule-container {
    padding: 20px;
}

.search-area {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 10px;
}

.search-item {
    display: flex;
    align-items: center;
}

.label {
    margin-right: 8px;
    white-space: nowrap;
}

.date-picker-area {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 20px;
}

.date-display {
    font-size: 16px;
    color: #606266;
    font-weight: bold;
}

.time-slots {
    display: flex;
    flex-direction: column;
    height: 120px;
}

.time-slots div {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #ebeef5;
}

.time-slots div:last-child {
    border-bottom: none;
}

.schedule-slots {
    display: flex;
    flex-direction: column;
    height: 120px;
}

.slot-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #ebeef5;
    color: #909399;
}

.slot-item:last-child {
    border-bottom: none;
}

.has-schedule {
    color: #409EFF;
    font-weight: bold;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>